package alibaba.java8datetimeapi;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.junit.jupiter.api.Test;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.*;

/**
 * @author ChangLiang
 * @date 2020/4/17
 */
public class ThreadLocalSimpleDateFormatTest {

    private static ThreadLocal<SimpleDateFormat> simpleDateFormatThreadLocal =
            ThreadLocal.withInitial(()->new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    /**
     * use threadFactoryBuilder to define a thread pool
     */
    private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();

    private static ExecutorService pool = new ThreadPoolExecutor(5, 200, 0L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());

    private static CountDownLatch countDownLatch = new CountDownLatch(100);

    @Test
    public void test() throws InterruptedException {

        Set<String> dates = Collections.synchronizedSet(new HashSet<>());
        for (int i = 0; i < 100; i++) {
            Calendar calendar = Calendar.getInstance();
            int finalI = i;
            pool.execute(()->{
                calendar.add(Calendar.DATE,finalI);
                String dateString = simpleDateFormatThreadLocal.get().format(calendar.getTime());
                dates.add(dateString);
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        System.out.println(dates.size());
        ArrayList list = Util.convertToSortedArrayList(dates);
        System.out.println(list);
    }
}
